define(function(require){
    var main = require('/static/main.js');
    var m = new main();
    var level = {
        isActive : false,
        activeindex :'',
        levelList : [],
        actionList : [],
        ENTCode :0,
        table : '',
        init:function(){
            this.bindEvent();
            this.getList();
        },
        getList:function(){
            //获取管理员列表
            //ajax请求数据
            $.ajax({
                type: "POST",
                url: "/jurisdiction/get-level-list",
                dataType: "json",
                success: function (result){
                    var str = '';
                    level.levelList = result.data;
                    $.each(result.data,function(k,v){
                        if(v.ENTCode == 'E000000'){
                            $(".EditLevel").show();
                        }
                       str += ' <div class="row"><div class="overflow">\
                        <div class="search_litile_tit fl" style="padding-left: 10px;margin-left: 10px;"><span class="tit_diswidth"></span> 管理 -> '+ v.LevelName+'</div>\
                    <div class="fr">';
                        if(v.ENTCode == 'E000000'){
                            str += '<button class="btn btn-primary  m-b-5 m-r-10 edit-add-btn EditLevel" data-type="200"> <i class="icon fa fa-edit" style="font-size: 15px;margin-right: 5px;"></i> 编辑</button>\
                        <button class="btn btn-primary  m-b-5 m-r-10 edit-add-btn DelLevel" style="background: #ff5f63;border: 1px solid #ff5f63;"> <i class="icon ion-trash-a" style="font-size: 17px;margin-right: 5px;"></i>删除</button>';
                        }
                        str += '<button class="btn btn-primary  m-b-5 m-r-10 edit-add-btn RoleUpdate changebgr"> <i class="icon fa  fa-save " style="font-size: 15px;margin-right: 5px;"></i> 保存等级关联</button>\
                    </div>\
                    </div>\
                    <div class="col-md-12 col-sm-12 col-xs-12">\
                        <table id="datatable'+k+'" class="table table-striped table-bordered dataTable no-footer">\
                            <thead>\
                                <tr class="">\
                                    <th style="width: 200px;;">模块</th>\
                                    <th>权限配置</th>\
                                </tr>\
                            </thead>\
                            <tbody></tbody></table>\
                        </div></div>';
                    });
                    $(".panel-body").html(str);
                    $.each(result.data,function(k,v){
                        level.ENTCode = v.ENTCode;
                        level.getLevel(v.MytipLevelId,k);
                    });
                }
            });

        },
        getLevel:function(id,tableid){
            $.ajax({
                type: "post",
                dataType: "json",
                url:  '/jurisdiction/level-action-get-list',
                data:{MytipLevelId:id},
                success: function (ret) {
                    var str = '';
                    $.each(ret.Models,function(k,v){
                        str += '<tr>\
                        <td>'+ v.ControllerName +'</td>\
                        <td data-cid="'+ v.ControllerId +'">';
                        $.each(v.ActionList,function(key,val){
                            str += '<label class="level-label"><input type="checkbox" value="" data-id="'+val.ActionId+'" '+(val.IsCheck ? 'checked': '')+'>'+val.ActionName+'</label>';
                        });
                        str += '</td></tr>';
                    });
                    $("#datatable"+tableid).find("tbody").html(str);
                    /*$("#datatable"+tableid).dataTable({
                        "searching":false,
                        'bLengthChange': false,
                        'bPaginate': true,
                        "bDestory": true,
                        "bRetrieve": true,
                        "bFilter":false,
                        "bSort": false,
                        "bProcessing": false,
                        "autoWidth": false,
                    });*/
                    $(".panel-default").fadeIn();
                }
            });

        },
        bindEvent:function(){
            //编辑
            $(document).on('click','.EditLevel',function(){
                var ENTCode = level.ENTCode;
                var type = $(this).attr('data-type');
                console.log(ENTCode);
                if(ENTCode == 'E000000' ){
                    if(type == '200'){
                        var index = $(this).closest(".row").index();
                        level.activeindex = index;
                        var data = level.levelList[index];
                        level.getopcion(index,data.ParentLevelId);
                        $(".ENTCodeInput").hide();
                        $("#EditLevel .LevelName").val(data.LevelName);
                    }else{
                        level.activeindex = '';
                        level.getopcion();
                        $(".ENTCodeInput").show();
                    }
                    $(".EntPriseInput").hide();
                }else{
                    if(type == '200'){
                        var index = $(this).closest(".row").index();
                        level.activeindex = index;
                        var data = level.levelList[index];
                        $("#EditLevel .LevelName").val(data.LevelName);
                        $("#EditLevel .BrokerageRatio").val(data.BrokerageRatio);
                        $("#EditLevel .PerformanceRatio").val(data.PerformanceRatio);
                        level.getopcion(index,data.ParentLevelId);
                    }else{
                        level.activeindex = '';
                        level.getopcion();
                    }
                }
                level.showmessage($("#EditLevel .error"),false);
                $("#EditLevel").modal('show');

            });
            //编辑提交
            $(document).on('click','#EditLevel .btn-sure',function(){
                var JsonData ={
                    LevelName : $("#EditLevel .LevelName").val().trim(),
                    PerformanceRatio : $("#EditLevel .PerformanceRatio").val().trim(),
                    BrokerageRatio : $("#EditLevel .BrokerageRatio").val().trim(),
                    ParentLevelId : $("#ParentLevelId").val().trim(),
                }
                if(!(level.activeindex.length == 0)){
                    var data = level.levelList[level.activeindex];
                    JsonData.MytipLevelId =  data.MytipLevelId;
                }
                if(JsonData.LevelName.length < 1){
                    level.showmessage($("#EditLevel .error"),true,'请输入管理员名称');
                    return false;
                }
                if(level.ENTCode != 'E000000'){
                    if(JsonData.PerformanceRatio.length < 1){
                        level.showmessage($("#EditLevel .error"),true,'请输入销售绩效比例');
                        return false;
                    }
                    if(JsonData.BrokerageRatio.length < 1){
                        level.showmessage($("#EditLevel .error"),true,'请输入绩效佣金比例');
                        return false;
                    }
                }

                level.showmessage($("#EditLevel .error"),false);
                level.resetFrom($("#EditLevel"));
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: '/jurisdiction/mytip-level-update',
                    data:JsonData,
                    success: function (ret) {
                        $("#EditLevel").modal('hide');
                        level.resetFrom($("#EditLevel"));
                        if(ret.IsBizSuccess){
                            if(level.activeindex == ''){
                                layer.msg('添加成功！');
                            }else{
                                layer.msg('修改成功！');
                            }
                            level.getList();
                        }else{
                            if(level.activeindex == ''){
                                layer.msg('添加失败！');
                            }else{
                                layer.msg('修改失败！');
                            }
                        }
                    }
                });
            });

            var Relationaction = false;
            //保存关联信息
            $(document).on('click','.RoleUpdate',function(){
                if(Relationaction){
                    return false;
                }
                var index = $(this).closest(".row").index();
                var _obj = $(this).closest(".row").find("tbody");
                    var actionList = new Array();
                    _obj.find('tr').each(function(k,v){
                        $(this).find("input").each(function(key,val){
                            if($(this).is(":checked")){
                                var cid = $(this).parents("td").data("cid");
                                var data = {ControllerId:cid,ActionId:$(this).data("id")};
                                actionList.push(data);
                            }
                        });

                    });
                    var JsonData = {MytipLevelId: level.levelList[index].MytipLevelId,Data:actionList};
                    Relationaction = true;
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: '/jurisdiction/level-action-save',
                        data: JsonData,
                        success: function (ret) {
                            Relationaction = false;
                            if(ret.IsBizSuccess){
                                layer.msg('操作成功！');
                            }else{
                                layer.msg('操作失败！');
                            }
                        }
                    });


            });

            //删除
            var delaction  = false;
            $(document).on('click','.DelLevel',function(){
                if(delaction){
                    return false;
                }
                var index = $(this).closest(".row").index();
                level.activeindex = index;
                var data = level.levelList[index];
                delaction = true;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: '/jurisdiction/employee-level-del',
                    data: {MytipLevelId:data.MytipLevelId},
                    success: function (ret) {
                        delaction = false;
                        level.getList();
                        if(ret.IsBizSuccess){
                            layer.msg('删除成功！');
                        }else{
                            layer.msg('删除失败！');
                        }
                    }
                });

            });
        },
        getopcion:function(index,levelid){
            if(typeof(index) != 'undefined'){
                if(level.levelList.length < 2){
                    $("#ParentLevelId").closest(".form-group").hide();
                }else{
                    var str = '<option value="">请选择上级</option>';
                    $.each(level.levelList,function(k,v){
                        if(k != index){
                            str += '<option value="'+ v.MytipLevelId+'" '+(levelid == v.MytipLevelId ? 'selected':'' )+'>'+ v.LevelName+'</option>';
                        }
                    });
                    $("#ParentLevelId").html(str);

                }
            }else{
                $("#ParentLevelId").closest(".form-group").show();
                var str = '<option value="">请选择上级</option>';
                $.each(level.levelList,function(k,v){
                    str += '<option value="'+ v.MytipLevelId+'">'+ v.LevelName+'</option>';
                });
                $("#ParentLevelId").html(str);
            }


        },
        showmessage:function(_obj,isshow,str){
            if(isshow){
                _obj.html(str).show();
            }else{
                _obj.html('').hide();
            }
        },
        //重置表单
        resetFrom:  function (_obj){
            _obj.find("form").each(function (index) {
                _obj.find("form")[index].reset();
            });
            level.showmessage(_obj.find(".error"),false);
        }
    }
    level.init();
});
